<template>
    <div class="sjplatformtree-bgwhite">
        <el-input v-model="filterText" placeholder="检索关键字..." />
        <el-tree ref="treeRef" class="filter-tree" :data="scheduleData.tree" :props="defaultProps" default-expand-all
            :filter-node-method="filterNode" :expand-on-click-node="false" @node-click="handleNodeClick">
            <template #default="{ node }">
                <el-tooltip v-if="isOverflowed(node)" class="item" effect="light" :content="node.label" placement="top">
                    <span class="tree-node-content" :data-id="node.id">{{
                        node.label
                        }}</span>
                </el-tooltip>
                <span v-else class="tree-node-content" :data-id="node.id">{{
                    node.label
                    }}</span>
            </template>
        </el-tree>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineExpose } from "vue";
import { ElTree } from "element-plus";
import { useProjectSchedule } from "../../../hooks/ProjectManager/Plan/useProjectSchedule";

interface Tree {
    id: string;
    label: string;
    children?: Tree[];
}

let receivedProps = defineProps(['projectId']);
let exposeNode = ref();
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
    children: "children",
    label: "label",
};

watch(filterText, (val) => {
    if (treeRef.value) {
        // 确保 treeRef 已经初始化
        treeRef.value.filter(val);
    }
});

const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.label.includes(value);
};

// 使用数据处理 Hook
const { scheduleData, getProjectScheduleTree } = useProjectSchedule(1, 10);
getProjectScheduleTree(receivedProps.projectId); // 调用数据获取方法

const handleNodeClick = (node) => {
    exposeNode.value = node;
};

function isOverflowed(node) {
    //  await nextTick();
    //   const element = document.querySelector(`.tree-node-content[data-id="${node.id}"]`) as HTMLElement;
    //   if (element) {
    //     console.log(element);
    //     console.log("element.offsetWidth:", element.offsetWidth, "element.scrollWidth:", element.scrollWidth);
    //     return element.offsetWidth < element.scrollWidth;
    //   }
    //   return false;
    return node.label.length > 13;
}

defineExpose({ exposeNode });
</script>